const { parseRule } = require('./parser')
const cheerio = require('cheerio')
const _ = require('lodash')
const request = require('./request')

function parseContent (source, doc) {
  const $ = cheerio.load(doc)

  const bookMap = {
    content: 'ruleBookContent'
  }

  const item = {}
  Object.keys(bookMap).forEach(prop => {
    item[prop] = _.trim(parseRule(source[bookMap[prop]], $))
  })

  return item
}

async function downloadContent (source, url) {
  if (!_.startsWith(url, 'http')) {
    url = source.bookSourceUrl + url
  }
  return request.get(url)
}

async function content (source, url) {
  const doc = await downloadContent(source, url)
  return parseContent(source, doc)
}

module.exports = {
  parseContent,
  downloadContent,
  content
}
